﻿@{
    ViewBag.Title = "Using Entity Framework 6 DbFunctions";
}

<h2>@ViewBag.Title</h2>

@Html.FormatMarkdown("**Dynamic LINQ** for .NET 4.0+ by default includes support for the **LINQ to Entities** [`System.Data.Objects.EntityFunctions`][0]. However, as **Entity Framework 6** is a NuGet package, and in order to avoid dependencies on that package, Dynamic LINQ does not natively support the newer [`DbFunctions`][1] helper functions.  This *How To* will show you how to set up Dynamic LINQ to use DbFunctions.\n\n[0]: https://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions(v=vs.110).aspx\n[1]: https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions(v=vs.113).aspx")

<h3>Step 1 - Implement a new Custom Type Provider</h3>

@Html.FormatMarkdown("For this example, we inherit from [`DefaultDynamicLinqCustomTypeProvider`][0] so we can continue to use the default behavior of Dynamic LINQ. If we do not want this, we could always implement the interface [`IDynamicLinkCustomTypeProvider`][1] directly.\n\n[0]: /Library/DefaultDynamicLinqCustomTypeProvider\n[1]: /Library/IDynamicLinkCustomTypeProvider")

@Html.FormatCodeBlock(@"class MyCustomTypeProvider 
    : DefaultDynamicLinqCustomTypeProvider 
{
    public override HashSet<type> GetCustomTypes()
    {
        //get the original set of custom types
        var result = base.GetCustomTypes(); 

        //Add DbFunctions as a custom type
        result.Add(typeof(System.Data.Entity.DbFunctions)); 

        return result;
    }
}")

<h3>Step 2 - Configure Dynamic LINQ to use MyCustomTypeProvider</h3>

@Html.FormatCodeBlock("System.Linq.Dynamic.GlobalConfig.CustomTypeProvider = new MyCustomTypeProvider();")

<h3>Result</h3>

@Html.FormatMarkdown("Everything is now set up. As an example, let's use [`DbFunctions.Reverse`][0] in a unit test.\n[0]: https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions.reverse(v=vs.113).aspx")

@Html.FormatCodeBlock(@"
var context = new BlogContext();

//Use Dynamic LINQ with DbFunctions
var test = _context.Blogs.Select(""DbFunctions.Reverse(Name)"").ToDynamicArray();

//Use standard LINQ to confirm result;
var expected = _context.Blogs.Select(x => DbFunctions.Reverse(x.Name)).ToArray();

//Confirm the result:
CollectionAssert.Equal(expected, test);")

@Html.FormatMarkdown("Note that if the custom type provider isn't set up correctly, you will get a [`ParseException`][0].\n[0]: /Library/ParseException")